import { getToken } from '@/utils/auth'

// 登录页面及友好别名
const loginPage = "/pages/pc/login"
const loginAliases = [loginPage, '/login']
  
// 页面白名单
const whiteList = [
  ...loginAliases,
  '/pages/pc/register', '/pages/pc/passwordForgot', '/pages/common/webview/index'
]

// 检查地址白名单
function normalizeLogin(p){ return p === '/login' ? loginPage : p }

function checkWhite(url) {
  const path = url.split('?')[0]
  return whiteList.includes(path)
}

// 页面跳转验证拦截器
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]
list.forEach(item => {
  uni.addInterceptor(item, {
    invoke(to) {
      if (getToken()) {
      if (loginAliases.includes(to.url)) {
          uni.reLaunch({ url: "/" })
        }
        return true
      } else {
        if (checkWhite(to.url)) {
          return true
        }
        uni.reLaunch({ url: loginPage })
        return false
      }
    },
    fail(err) {
      console.log(err)
    }
  })
})

// H5 地址栏直达首屏强校验 (history 模式)
// #ifdef H5
function getCurrentPath() {
  try {
    const pathname = window.location.pathname || '/'
    return (pathname.split('?')[0] || '/')
  } catch(e) { return '/' }
}

function enforceAuthOnPath() {
  const token = getToken()
  let path = getCurrentPath()
  if (path === '/login') path = loginPage
  const inWhite = checkWhite(path)
  if (!token) {
    if (!inWhite) {
      if (window.location.pathname !== loginPage) {
        window.history.replaceState(null, '', loginPage)
        // 触发 uni 框架路由进入
        uni.reLaunch({ url: loginPage })
      }
    }
  } else if (loginAliases.includes(path)) {
    uni.reLaunch({ url: '/pages/pc/index' })
  }
}

document.addEventListener('DOMContentLoaded', enforceAuthOnPath)
window.addEventListener('popstate', enforceAuthOnPath)
// #endif
